#bilibili排名算法 v2.1(2010.11.15)
#没有实质性的变化，添加一些分析用数据
class Results::R21 < Results::R20

   def get_es
     self.get_es nil, self.scan_id
   end

   def self.get_es scan_id_from=nil, scan_id_to=nil
     #scan_id1和scan_id2可以是scans的id，也可以是查询后的数组
     if scan_id_to.class == Array
       results1 = scan_id_from
     else
       results1 = Result.find :all, :include => :work,
                           :conditions => ["results.scan_id = ? and works.status = 1", scan_id_from.to_i]
     end
     if scan_id_to.class == Array
       results2 = scan_id_to
     else
       scan_id_to = scan_id_to || Scan.last.id
       results2 = Result.find :all, :include => :work,
                           :conditions => ["results.scan_id = ? and works.status = 1 and works.ac_type_id != 18", scan_id_to]
     end
     results = {}
     results2.each{|r2| results[r2.work.id] = r2}
     unless results1.empty?
       results1.each do |r1|
         if results[r1.work.id]
           results[r1.work.id].clicks -= r1.clicks
           results[r1.work.id].comments -= r1.comments
           results[r1.work.id].stows -= r1.stows.to_i
           results[r1.work.id][:old] = true
        end
       end
       #删除错误数据
       last_wid = Result.maximum("works.wid", :include => :work, :conditions => ["scan_id = ?", scan_id_from]).to_i
       results.select{|i, r| !r[:old] && r.work.wid <= last_wid }.each{|i, r| results.delete i}
     end
    #收藏数前1000名收藏率倒数之和
    t_r = 0
    results.values.sort_by{|r| r.stows.to_i}.reverse[3..999].each do |r|
      t_r += r.clicks / r.work.part_count / r.stows
    end
    @e_s = t_r / 997
    #results
   end
end
